package com.zy.rest.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.zy.common.util.JsonUtils;
import com.zy.common.util.TaotaoResult;
import com.zy.mapper.TbItemDescMapper;
import com.zy.mapper.TbItemMapper;
import com.zy.pojo.TbItem;
import com.zy.pojo.TbItemDesc;
import com.zy.rest.dao.JedisClient;
import com.zy.rest.service.ItemService;

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private TbItemDescMapper itemDescMapper;
	@Autowired
	private JedisClient jedisClient;

	// 取redis的基础key
	@Value("${REDIS_ITEM_KEY")
	private String REDIS_ITEM_KEY;

	// 取redis的缓存时间
	@Value("${REDIS_ITEM_EXPIRE}")
	private int REDIS_ITEM_EXPIRE;

	@Override
	public TaotaoResult getItemBaseInfo(Long itemId) {
// 添加缓存逻辑
// 从缓存中提取数据
		try {
			// key值比较形象，组合方式，通过key值获取
			String json = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":base");
			if (!StringUtils.isBlank(json)) {
				// 转成对象
				TbItem item = JsonUtils.jsonToPojo(json, TbItem.class);
//				System.out.println("我从商品缓存中读取数据的幺");
				return TaotaoResult.ok(item);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

// 执行查询语句
		TbItem selectByPrimaryKey = itemMapper.selectByPrimaryKey(itemId);

// 放入缓存中
		try {
			if (selectByPrimaryKey != null) {
				// 转成字符串
				String objectToJson = JsonUtils.objectToJson(selectByPrimaryKey);
				// 放入缓存
				jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":base", objectToJson);
				// 设置有效期
				jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":base", REDIS_ITEM_EXPIRE);
//				System.out.println("添加新商品缓存成功,将于一天后过期");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return TaotaoResult.ok(selectByPrimaryKey);
	}

	/**
	 * 取商品描述
	 */
	@Override
	public TaotaoResult getItemDesc(Long itemId) {
		// 添加缓存逻辑
		// 从缓存中取商品描述
		try {
			String json = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":desc");
			// 判断是否有值
			if (!StringUtils.isBlank(json)) {
				TbItemDesc itemDesc = JsonUtils.jsonToPojo(json, TbItemDesc.class);
				return TaotaoResult.ok(itemDesc);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		TbItemDesc selectByPrimaryKey = itemDescMapper.selectByPrimaryKey(itemId);

		try {
			String objectToJson = JsonUtils.objectToJson(selectByPrimaryKey);
			// 把商品描述写入缓存（设置key的有效期）
			jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":desc", objectToJson);
			// 设置key的有效期
			jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":desc", REDIS_ITEM_EXPIRE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TaotaoResult.ok(selectByPrimaryKey);
	}

}
